<?php
class AppController extends Controller {
    var $helpers = array(
        'Html', 'Javascript', 'Form', 'Time', 'Session'
    );
    var $components = array(
        'Auth', 'Session', 'Cookie'
    );
    var $uses = array('Setting');
    
    function beforeFilter() {
        // check installation
        $setting = $this->Setting->find('first', array(
            'recursive' => -1
        ));

        if ( isset($setting['Setting']['is_installed']) ) {
            
        }
        
        $controller = $this->params['controller'];
        $action = $this->params['action'];
        $this->set('controller', $controller);
        $this->set('action', $action);
        $url = $this->params['url']['url'];
        if ( substr($url, 0, 1) != '/' ) {
            $url = '/' . $url;
        }
        
        if ( !$this->Cookie->read('Previous.url') ) {
            $this->Cookie->write('Previous.url', $url);
            $this->Cookie->write('Previous.hoop', 0);
        } else {
            $lastUrl = $this->Cookie->read('Last.url');
            if ($lastUrl != $url) {
                $hoop = $this->Cookie->read('Previous.hoop') + 1;
                $this->Cookie->write('Previous.hoop', $hoop);
                $this->Cookie->write('Previous.url', $lastUrl);
            } else {
                $this->Cookie->delete('Previous.hoop', 0);
                $this->Cookie->write('Previous.url', $lastUrl);
            }
        }
        $this->Cookie->write('Last.url', $url);
        
        $this->Auth->authorize = 'controller';
        $this->Auth->loginError = 'Username/password salah';
        $this->Auth->authError = 'Anda perlu login';
        
        $showLoginOnTop = true;
        $showRegisterOnTop = true;
        if ( $controller == 'users' ) {
            $showLoginOnTop = false;
            $showRegisterOnTop = false;
        }
        
        $showProfile = false;
        $profile = array();
        $isAdmin = false;
        if ( $this->Auth->user('id') ) {
            $showLoginOnTop = false;
            $showRegisterOnTop = false;
            
            $showProfile = true;
            $profile = $this->Auth->user();
            
            if ( $this->Auth->user('type') == 'admin' ) {
                $isAdmin = true;
                $this->Auth->allow('*');
            }
        }
        
        $this->set(compact('showLoginOnTop', 'showRegisterOnTop', 'showProfile', 'profile', 'isAdmin'));
    }
}
